package com.tensquare.spit.service;

import com.tensquare.spit.dao.SpitRepository;
import com.tensquare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.IdWorker;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SpitService {
    @Autowired
    private SpitRepository spitRepository;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 增加
     */
    public void saveSpit(Spit spit) {
        // 添加id
        spit.setId(idWorker.nextId() + "");
        // 设置默认值
        spit.setPublishtime(new Date());//发布时间为当前时间
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态
        // 保存新的吐槽
        this.spitRepository.save(spit);
        if (spit.getParentid() != null || "".equals(spit.getParentid())){
            // 有父级id,说明是吐槽别人的吐槽。给别人的回复值+1
            this.mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(spit.getParentid())), new Update().inc("comment", 1), "spit");
        }
    }

    /**
     * 删除
     */
    public void deleteSpit(String id) {
        this.spitRepository.deleteById(id);
    }

    /**
     * 修改
     */
    public void updateSpit(Spit spit) {
        this.spitRepository.save(spit);
    }

    /**
     * 查询全部
     */
    public List<Spit> findAll() {
        return this.spitRepository.findAll();
    }

    /**
     * 根据id查询
     */
    public Spit findSpitById(String id) {
        return this.spitRepository.findById(id).get();
    }

    /**
     * 根据上级ID查询吐槽列表（分页）
     */
    public Page<Spit> findByParentid(String parentId, int pageNum, int size) {
        return spitRepository.findByParentid(parentId, PageRequest.of(pageNum - 1, size));
    }


    /**
     * 点赞- 效率低
     */
    public void updateSpitThumbupToIncrementingOld(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.inc("thumbup", 1);
        this.mongoTemplate.updateFirst(query, update, "spit");
    }
}
